<template>
  <view class="timepicker">
      <view class="slider-year-month">
        <image :src="arrow_right" @click="getPreMonthDayList" class="pre"></image>
        <view class="year">
          <view class="month" >{{monthTitle}}</view>
          <view class="score">{{$common.parseFloatFixed(score_num)}}</view>
        </view>
        <image :src="arrow_right" @click="getNextMonthDayList" class="next">
        </image>
      </view>
      <view class="slider-week">
        <text class="week-item" :key="key" v-for="(item, key) in weekText">{{item}}</text>
      </view>
      <view class="slider-day">
        <view v-show="!item.isThisMonth"  :class="['day-item',item.isThisMonth?'':'not-current-month']" :key="key"
              v-for="(item, key) in days" @click="changeSelItem(item,key)">
          <view class="day">
            <view  class="day_ri">{{item.day}}</view >
            <view class="day_score w-100 ac">{{ $common.parseFloatFixed(item.score,item.isThisMonth)}}</view >
          </view>
        </view>
      </view>
    </view>
</template>
<script>
import {
  formatDate,
  returnData,
  getFirstAndLast,
  isToday
} from './day.js'
import {getScoreLists} from '@/api/user/userScore'

export default {
  name: "timepicker",
  data() {
    return {
      weekText: ["日", "一", "二", "三", "四", "五", "六"],
      currentDay: '', //当前几号
      currentYear: '', //当前年
      currentMonth: '', // 当前月
      currentWeek: '', // 当前月1号是星期几？ 0表示星期天
      monthTitle: '',
      arrow_right:"",
      arrow_lelf:"",
      thisMonthDay: [],
      days: [], //所有日期
      daysLists: [], //所有日期
      data_list: [], //所有日期
      firstDay: new Date(),
      weekDay: new Date().getDay(), //获取今天是周几
      selIndex: -1,
      score_num: 0,
      shaiPic:""
    };
  },
  computed: {},
  created() {
    this.firstDay.setDate(this.firstDay.getDate() - this.weekDay); //获取本周第一天的日期
    this.initData()
  },

  methods: {

    async getScoreList(time) {
      let that = this;
      that.score_num = 0
      let {data,code,status} = await getScoreLists({type:1,'time':time});
      if (status==0){
        const valueMap = {};
        const mergedData  = {};
        if(data.length!=0){
          data.forEach(item => {
            valueMap[item.times] = parseInt(item.value)!=0?(item.value).toFixed(2):0;
          });
          this.daysLists.forEach(item => {
            if (valueMap[item.d]) {
              item.score = valueMap[item.d];
              that.score_num+=parseFloat(item.score)
            }
          });
          that.days = that.daysLists;
        }else{
          that.days =that.daysLists;
          that.score_num = 0
        }
      }else {
        that.days = that.daysLists;
        that.score_num = 0
      }
      console.log( that.days)

    },

    // 选中日期
    changeSelItem(item, index) {
      this.selIndex = index;
      this.$emit('clickCurrentDay', item)
    },
    // 下月
    getNextMonthDayList() {
      this.pickNext(this.currentYear, this.currentMonth);
      console.log("this.currentYear, this.currentMonth")
    },
    // 上月
    getPreMonthDayList() {
      this.pickPre(this.currentYear, this.currentMonth);
    },
    // 上一月 （@param year, @param month）
    pickPre(year, month) {
      console.log("上一月")
      var d = new Date(formatDate(year, month, 1));
      d.setDate(0); //设置为上个月
      this.initData(formatDate(d.getFullYear(), d.getMonth() + 1, 1));
      this.$emit('currentYM', {
        year: this.currentYear,
        month: this.currentMonth
      })
    },
    // 下一个月 （@param year, @param month）
    pickNext(year, month) {
      console.log("下一个月")
      var d = new Date(formatDate(year, month, 1));
      d.setDate(35);
      this.initData(formatDate(d.getFullYear(), d.getMonth() + 1, 1));

      this.$emit('currentYM', {
        year: this.currentYear,
        month: this.currentMonth
      })
    },
    // 初始化月
    initData(cur) {
      var date;
      let that = this;
      if (cur) {
        // 切换上一月、下一月
        date = new Date(cur);
      } else {
        var now = new Date(); // 此处取本机时间，应改为服务器时间
        // console.log(now.getFullYear(), now.getMonth() + 1, 1)
        var date = new Date(formatDate(now.getFullYear(), now.getMonth() + 1, 1));
      }

      that.currentDay = new Date().getDate(); // 今日日期 几号
      that.currentYear = date.getFullYear(); // 当前年份
      that.currentMonth = date.getMonth() + 1; // 当前月份
      that.currentWeek = date.getDay(); // 当前月1号是星期几？ 0表示星期天
      // console.log(this.currentYear, this.currentMonth)
      var month = this.currentMonth >= 10 ? this.currentMonth : "0" + that.currentMonth;
      that.monthTitle = this.currentYear + " 年 " + month+" 月";
      this.getScoreList( this.currentYear + "-" + month+"-01")

      // 当前月最后一天是星期几？ 0表示星期天
      var nextWeek = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDay();
      var str = formatDate(that.currentYear, that.currentMonth, 1); // 2021/05/01
      var nextStr = new Date(
          date.getFullYear(),
          date.getMonth() + 1,
          0
      ).toLocaleDateString(); // 2021/05/31
      var daysList = []; // 初始化日期
      // 设置上一个月 需显示 的最后几天  铺满一周
      for (var i = that.currentWeek; i > 0; i--) {
        var d = new Date(str);
        d.setDate(d.getDate() - i);
        var tod = returnData(d); //获取完整日期
        var dayobject = {
          d: tod,
          data: tod,
          day: d.getDate(),
          isThisMonth: d.getMonth() + 1 == that.currentMonth ? true : false,
          isToDay: isToday(tod),
          score:0,
        }; // 用一个对象包装Date对象  以便为以后预定功能添加属性
        daysList.push(dayobject); // 将日期放入data 中的days数组 供页面渲染使用
      }
      // 显示当前月的天数  第二个循环为 j<= 36- currentWeek，
      // 因为1号是星期六的时候当前月需显示6行，如2020年8月
      var num = 0; //第几个月 每遇到1号加1
      for (var j = 0; j <= 36 - that.currentWeek; j++) {
        var d = new Date(str);
        d.setDate(d.getDate() + j);
        var tod = returnData(d); //获取完整日期
        var dddd = d.getDate();
        var dayobject = {
          d: tod,
          data: tod,
          day: d.getDate(),
          isThisMonth: d.getMonth() + 1 == that.currentMonth ? true : false,
          isToDay: isToday(tod),
          score: 0,
        };
        if (dddd == 1) {
          num++;
        }
        if (num == 2) {
          break;
        }
        daysList.push(dayobject);
      }
      // 设置下一个月 需显示 的最前几天铺满一周
      for (var k = 1; k <= 6 - nextWeek; k++) {
        var d = new Date(nextStr);
        d.setDate(d.getDate() + k);
        var tod = returnData(d); //获取完整日期
        var dayobject = {
          d: tod,
          data: tod,
          day: d.getDate(),
          isThisMonth: d.getMonth() + 1 == that.currentMonth ? true : false,
          isToDay: isToday(tod),
        }; // 用一个对象包装Date对象  以便为以后预定功能添加属性
        daysList.push(dayobject); // 将日期放入data 中的days数组 供页面渲染使用
      }
      // 设置本月的所有日期
      that.thisMonthDay = daysList.filter((item, index) => {
        if (isToday(item.d)) {
          that.selIndex = index;
        }
        return item.isThisMonth
      })
      that.daysLists = daysList;
    },
  }
};
</script>
<style lang="scss" scoped>
.timepicker {
  width: 100%;
  padding: 0 15rpx;
  box-sizing: border-box;
        .slider-year-month {
          padding: 12rpx 10%;
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 80rpx;
          margin: 50rpx;

          .year{
            background: url("");
            background-size: cover; /* 使背景图片覆盖整个元素 */
            background-repeat: no-repeat; /* 防止背景图片重复 */
            background-position: center; /* 使背景图片居中显示 */
            width: 238rpx;
            height: 77rpx;
              border-radius: 13rpx;
            align-items: center;
            justify-content: center;
            text-align: center;
            font-size: 26rpx;
            color: #fff;
            padding: 6rpx 0;
            .month{

            }
            .score{
              //color: #df2f39;
              font-size: 24rpx;
            }
          }
          .pre {
            width: 17rpx;
            height: 30rpx;
            transform: rotate(180deg);
            background: url("");
            background-repeat: no-repeat; /* 防止背景图片重复 */

            justify-content: center;
          }

          .next {
            width: 17rpx;
            height: 30rpx;
            background: url("");

          }
        }

        .slider-week {
          display: flex;
          font-weight: bold;
          align-items: center;
          color: #333;

          .week-item {
            flex: 1;
            font-size: 32rpx;
            padding: 15rpx 0 20rpx;
            border-bottom: 1px solid #eee;
            text-align: center;
          }
        }

        .slider-day {
          //padding: 10rpx 0;
          padding-top: 10rpx;
          display: flex;
          flex-wrap: wrap;

          .day-item {
            justify-content: center;
            align-items: center;
            //padding: 10px;
            border: 1px solid #ddd;
            min-height: 40px;

            background-color: #e2e9fb;
            border-radius: 12rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #333;
            //width: 13.28%;
            width: 91rpx;
            height: 91rpx;
            text-align: center;
            font-size: 28rpx;
            margin: 0.5rpx;

            .day {
              //width: 70rpx;
              // line-height: 70rpx;
              // height: 70rpx;
              border-radius: 50%;
              position: relative;
            }
            .day_ri{

            }
            .day_score{
              color: #df2f39;
              font-size: 22rpx;
            }

            .sel:after {
              position: absolute;
              display: block;
              content: "";
              width: 6rpx;
              height: 6rpx;
              margin: auto;
              border-radius: 50%;
              background: #677FD2;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }

          .day-item-current {
            color: red;
            background: #EAEAEA;
          }

          .day-item-sel {
            background: #677FD2;
            color: #fff;
          }


          .not-current-month {
            .day {
              color: #c9c6c6;
            }
          }
    }

    .box-footer {
      flex-basis: 10%;
      display: flex;
      box-shadow: 0px -1px 0px #eee;

      .footer-btn {
        flex: 1;
        text-align: center;

        span {
          font-size: 16px;
        }

        &:not(:last-child) {
          box-shadow: 1px 0px 0px #eee;
        }
      }
    }
}
</style>
